package com.macro.mall.tiny.modules.ums.service.impl;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.service.RedisService;
import com.macro.mall.tiny.modules.ums.mapper.CourseMapper;
import com.macro.mall.tiny.modules.ums.model.Course;
import com.macro.mall.tiny.modules.ums.model.bo.CourseBO;
import com.macro.mall.tiny.modules.ums.model.bo.CourseRedisBO;
import com.macro.mall.tiny.modules.ums.model.bo.CourseSelectBO;
import com.macro.mall.tiny.modules.ums.model.vo.CourseVO;
import com.macro.mall.tiny.modules.ums.service.CourseService;

import com.macro.mall.tiny.util.ExcelUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: i_kun
 * @Desc: o_。
 * @create: 2025-06-26 09:18
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public Page listPage(CourseSelectBO courseSelectBO) {
        /**
         * 获取当前登陆人的信息
         */
        //TODO 根据不同账号进来要看到不同内容
        //查询
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",1);
        if (courseSelectBO.getCourseName()!= null){
            queryWrapper.like("course_name",courseSelectBO.getCourseName());
        }
        if (courseSelectBO.getStartTime()!= null){
            queryWrapper.ge("start_time",courseSelectBO.getStartTime());
        }
        if (courseSelectBO.getEndTime()!= null){
            queryWrapper.le("end_time",courseSelectBO.getEndTime());
        }
        queryWrapper.orderByDesc("id");
        //分页
        Page<Course> page = new Page<>(courseSelectBO.getPageNum(), courseSelectBO.getPageSize());
        //redis 缓存所有课程
        List<Course> courses = courseMapper.selectList(queryWrapper);
        List<CourseRedisBO> courseRedisBOS = new ArrayList<>();
        for (Course cours : courses) {
            CourseRedisBO courseRedisBO = new CourseRedisBO();
            courseRedisBO.setId(cours.getId());
            courseRedisBO.setCourseName(cours.getCourseName());
            courseRedisBOS.add(courseRedisBO);
        }
        redisService.set("courses_list_Id", courseRedisBOS);


        return courseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 更改课信息
     *
     * @param courseBO
     */
    @Override
    public void inst(CourseBO courseBO) {
        //新增课程校验名称重复
        //课程名称不能重复
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("course_name",courseBO.getCourseName());
        wrapper.eq("is_del",1);
        List<Course> courseList = courseMapper.selectList(wrapper);
        if (courseList.size() > 0){
            CommonResult.failed("课程名称不能重复");
        }
        Course course = new Course();
        course.setCourseName(courseBO.getCourseName());
        course.setContent(courseBO.getContent());
        course.setImg(courseBO.getImg());
        course.setRemark(courseBO.getRemark());
        course.setIsDel(1);
        course.setNum(0);
        course.setCreateTime(new Date());
        course.setUpdateTime(new Date());
        course.setUpdateBy(courseBO.getOperator());
        courseMapper.insert(course);
    }

    /**
     * 新增课程根据redis 来判断是否成名称重复
     *
     * @param courseBO
     */
    @Override
    public CommonResult instRedis(CourseBO courseBO) {
        //优先去查redis中已经缓存的课程信息
        //一定要记得    数据的一致性！！！  定时同步数据
        Object objList = redisService.get("courses_list_Id");
        //objList 集合转 List<CourseRedisBO>
        ArrayList<CourseRedisBO> list =    (ArrayList<CourseRedisBO>) objList;
        for (CourseRedisBO courseRedisBO : list) {
            if (courseBO.getCourseName().equals(courseRedisBO.getCourseName())){
              return CommonResult.failed("课程名称不能重复");
            }
        }
        //可以进行正常的新增课程流程
        Course course = new Course();
        course.setCourseName(courseBO.getCourseName());
        course.setContent(courseBO.getContent());
        course.setImg(courseBO.getImg());
        course.setRemark(courseBO.getRemark());
        course.setIsDel(1);
        course.setNum(0);
        course.setCreateTime(new Date());
        course.setUpdateTime(new Date());
        course.setUpdateBy(courseBO.getOperator());
        courseMapper.insert(course);
        return   CommonResult.success(null);
    }

    /**
     * 保证redis与数据库中的数据一致
     * @param courseBO
     */
    @Override
    public CommonResult instRedisCourse(CourseBO courseBO){
        //优先去查redis中已经缓存的课程信息
        Object objList = redisService.get("courses_list_Id");
        //objList 集合转 List<CourseRedisBO>
        ArrayList<CourseRedisBO> list = (ArrayList<CourseRedisBO>) objList;
        for (CourseRedisBO courseRedisBO : list) {
            if (courseBO.getCourseName().equals(courseRedisBO.getCourseName())){
                return CommonResult.failed("课程名称不能重复");
            }
        }
        //校验通过了 开始新增 优先写入mysql
        //可以进行正常的新增课程流程
        Course course = new Course();
        course.setCourseName(courseBO.getCourseName());
        course.setContent(courseBO.getContent());
        course.setImg(courseBO.getImg());
        course.setRemark(courseBO.getRemark());
        course.setIsDel(1);
        course.setNum(0);
        course.setCreateTime(new Date());
        course.setUpdateTime(new Date());
        course.setUpdateBy(courseBO.getOperator());
        //insert 执行这条sql新增了多少条数据
        int insert = courseMapper.insert(course);
        if (insert>0){
            CourseRedisBO courseRedisBO = new CourseRedisBO();
            courseRedisBO.setId(course.getId());
            courseRedisBO.setCourseName(course.getCourseName());
            list.add(courseRedisBO);
            redisService.set("courses_list_Id",list);
        }
        return CommonResult.success(null);
    }


    @Override
    public CommonResult delRedisKey() {
        dingshi();
        return null;
    }


    /**
     * 定时任务
     * @return
     */
    public CommonResult dingshi() {
        //定时同步我们的mysql中的数据
        //优先采用mysql中
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",1);
        List<Course> courses = courseMapper.selectList(queryWrapper);
        //直接转换缓存到redis
        ArrayList<CourseRedisBO> courseRedisBOS = new ArrayList<>();
        redisService.del("courses_list_Id");
        if (courses != null && courses.size()>0){
            for (Course cours : courses) {
                CourseRedisBO courseRedisBO = new CourseRedisBO();
                BeanUtils.copyProperties(cours, courseRedisBO);
                courseRedisBOS.add(courseRedisBO);
            }
        }
        redisService.set("courses_list_Id",courseRedisBOS);
        return null;
    }

    /**
     * 导出课程
     *
     * @param courseBO
     *
     */
    @Override
    public void export( HttpServletResponse response ,CourseBO courseBO) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("course_name",courseBO.getCourseName());
        wrapper.eq("is_del",1);
        List<Course> courseList = courseMapper.selectList(wrapper);
        ExportParams exportParams = new ExportParams("课程数据_", "课程数据_", ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Course.class, courseList);
        try {
            String fileName = "课程数据_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入课程
     *
     * @param file
     *  ExcelUtil<ImportsDeptBO> util = new ExcelUtil<ImportsDeptBO>(ImportsDeptBO.class);
     */
    @Override
    public void imports(MultipartFile file) {

    }


    /**
     * 导出课程demo
     *
     * @param response
     * @param courseBO
     */
    @Override
    public void exportDemo(HttpServletResponse response, CourseBO courseBO) throws IOException {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 1);
        if (courseBO.getCourseName() != null){
            queryWrapper.like("course_name", courseBO.getCourseName());
        }
        //数据体量不大可以直接查询
        List<Course> courses = baseMapper.selectList(queryWrapper);
        //转VO 不为空
        if (CollUtil.isNotEmpty(courses)){
            ArrayList<CourseVO> courseVOList = new ArrayList<>();
            for (Course cours : courses) {
                CourseVO courseVO = new CourseVO();
                BeanUtils.copyProperties(cours, courseVO);
                courseVOList.add(courseVO);
            }
            //去构建导出文件的相关信息
            ExportParams exportParams = new ExportParams("课程表","第一页",ExcelType.XSSF);
            //workbook创建
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CourseVO.class, courseVOList);
            ExcelUtil.export(response,workbook, "课程表");
        }
    }

    /**
     * 导入文件
     *
     * @param file
     */
    @Override
    public void importsDemo(MultipartFile file) throws Exception {
        //导入
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<CourseVO> list = ExcelImportUtil.importExcel(file.getInputStream(), CourseVO.class, params);
        ArrayList<Course> courseList = new ArrayList<>();
        for (CourseVO courseVO : list) {
            Course course = new Course();
            course.setRemark("导入新增的");
            course.setContent("XXXX");
            course.setIsDel(1);
            course.setNum(0);
            course.setUpdateBy(courseVO.getCreateBy());
            course.setUpdateTime(new Date());
            course.setImg("XXX");
            course.setCourseName(courseVO.getCourseName());
            course.setCreateBy(courseVO.getCreateBy());
            course.setCreateTime(new Date());
            courseList.add(course);
        }
        saveBatch(courseList);
    }

    /**
     * 定时去更新redis中得课程信息
     */
    @Override
    public void listJob() {
        //获取所有课程
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",1);
        List<Course> courses = baseMapper.selectList(queryWrapper);
    }

    /**
     * 测试
     *
     * @param courseSelectBO
     * @return
     */
    @Override
    public List<Course> listDemo(CourseSelectBO courseSelectBO) {
        if (courseSelectBO.getCourseName()!= null){
            baseMapper.listDemo(courseSelectBO.getCourseName());
        }

        return null;
    }

    /**
     * 测试
     */
    @Override
    public void demo2() {
        //这里面去实现具体业务
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",1);
        //获取到了所有的课程
        List<Course> courses = baseMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(courses)){
            //同步到redis
            redisService.del("courses_list");
            ArrayList<CourseRedisBO> courseRedisBOS = new ArrayList<>();
            for (Course cours : courses) {
                CourseRedisBO courseRedisBO = new CourseRedisBO();
                BeanUtils.copyProperties(cours, courseRedisBO);
                courseRedisBOS.add(courseRedisBO);
            }
            redisService.set("courses_list",courseRedisBOS);
        }


    }
}
